<script lang="ts" setup>
import { ref, onMounted, nextTick, computed } from 'vue'
import { ElMessage, ElTree } from 'element-plus'
import { useRoute } from 'vue-router'
import TreeUtilDTO from '@/utils/tree'
import wsjzglService from '@/api/wsjzgl'
import lodash from 'lodash'
const route = useRoute()
const emit = defineEmits(['nodeClick', 'nodeCheck'])
const props = defineProps<{
  checkDisabled: boolean
  showCheckbox: boolean
}>()

// 生命周期
onMounted(() => {
  // 查询树
  // queryTree()
})
const treeData = ref<any>([])
const treeRef = ref<InstanceType<typeof ElTree>>()
const originalTreeData = ref<any>([])
/*
 * 查询树
 */
const firtsNode = ref<any>()
const queryTree = () => {
  //处理数据
  const params = {
    bmsah: route.query.bmsah as string,
    dwbm: route.query.cbdwbm as string,
  }
  wsjzglService
    .queryDzjzml(params)
    .then((res) => {
      if (res.data && res.data.length) {
        originalTreeData.value = lodash.cloneDeep(res.data)
        let obj = route.query
        res.data.forEach((item: any) => {
          if (!item.fmlbh) {
            item['fmlbh'] = obj.ajbh
          }
        })
        // //处理数据
        res.data.push({
          ajbhaj: obj.ajbh,
          mlbh: obj.ajbh,
          mlxsmc: obj.ajmc,
          wjsl: 0,
        })
        treeData.value = TreeUtilDTO.getTreeData(res.data, 'mlbh', 'fmlbh')
        if (treeData.value.length) {
          firtsNode.value = null
          // 递归选择第一个
          getFirstNode(treeData.value)
          if (firtsNode.value) {
            handleCheckNode(firtsNode.value)
          }
        }
      } else {
        treeData.value = []
        originalTreeData.value = []
      }
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
}

const init = () => {
  // 查询树
  queryTree()
}

const getFirstNode = (arr: any[]) => {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i].children && arr[i].children.length > 0) {
      getFirstNode(arr[i].children)
    } else {
      firtsNode.value = arr[i]
    }
    return
  }
}

/**
 *
 * @param node
 * @param flag 是滚动翻页，只改变样式
 */
const handleCheckNode = (node: any, flag?: boolean) => {
  if (!flag) treeNodeClick(node)
  nextTick(() => {
    treeRef.value!.setCurrentKey(node.mlbh)
  })
}

const defaultProps = computed(() => ({
  children: 'children',
  label: 'mlxsmc',
  disabled: () => {
    return props.checkDisabled
  },
}))

const treeNodeData = ref()
/*
 * 树节点点击（抛出方法到主界面）
 */
const treeNodeClick = (data: any) => {
  treeNodeData.value = data
  let dzjzList: any[] = []
  if (data.cj === '2') {
    const ml = originalTreeData.value.find((el: any) => el.mlbh === data.fmlbh)
    const aj = originalTreeData.value.find((el: any) => el.mlbh === ml?.fmlbh)
    const ajNode = TreeUtilDTO.findNode(treeData.value, aj?.mlbh || ml?.mlbh, 'mlbh')
    dzjzList = TreeUtilDTO.flatten([ajNode] || []).filter((el) => el.cj === '2')
  }
  emit('nodeClick', treeNodeData.value, dzjzList)
}

const checkChange = (node: any, e: any) => {
  emit('nodeCheck', [...e.halfCheckedNodes, ...e.checkedNodes])
}

defineExpose({ init, handleCheckNode })
</script>
<template>
  <div class="container">
    <div class="bottom">
      <el-tree
        ref="treeRef"
        style="max-width: 600px"
        :data="treeData"
        node-key="mlbh"
        highlight-current
        default-expand-all
        :expand-on-click-node="false"
        :props="defaultProps"
        :show-checkbox="showCheckbox"
        @node-click="treeNodeClick"
        @check="checkChange"
      >
        <template #default="{ data }">
          <div class="custom-tree-node">
            <!-- <el-icon v-if="data.fbh"> <FolderOpened /></el-icon> -->
            <img v-if="!data.fmlbh" src="/src/assets/images/file-icon.png" alt="" />
            <img v-if="data.cj === '1'" src="/src/assets/images/file-icon.png" alt="" />
            <img v-if="data.cj === '2'" src="/src/assets/images/text-icon.png" alt="" />
            <!-- <el-icon v-if="data.zrz"> </el-icon> -->
            <span :class="data.cj === '2' ? 'over-title' : ''" :title="data.mlxsmc"
              >&nbsp;{{ data.mlxsmc }}&nbsp;</span
            >
            <!-- <span>({{ data.wjsl }})</span> -->
          </div>
        </template>
      </el-tree>
    </div>
  </div>
</template>
<style lang="scss" scoped>
.container {
  width: 100%;
  height: 100%;

  .bottom {
    .tree_rightmenu {
      position: fixed;
      width: 120px;
      border: 1px solid rgba(0, 0, 0, 0.15);
      box-shadow: 0 6px 12px rgba(0, 0, 0, 0.175);
      z-index: 1000;
      background-color: #fff;
      display: flex;
      flex-direction: column;
      align-items: center;
    }
  }
}

.custom-tree-node {
  width: calc(100% - 40px);
  display: flex;
  align-items: center;
  .over-title {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
}
</style>
